
import { IncomingMessage, ServerResponse } from "http";
import fs from 'fs';
import url from 'url';
import path from 'path';

export const list = async (req: IncomingMessage, res: ServerResponse) => {
    try {
        const parsedUrl = url.parse(req.url || '', true);
        const { mid } = parsedUrl.query as { mid: string };

        const capabilityPath = path.join(__dirname, '../../../../src/modules', mid, 'capabilityHooks');
        const capabilitys = getDirectories(capabilityPath)
            .map(e=>{
                const str = fs.readFileSync(path.join(e, 'index.tsx'), 'utf-8')
                return {
                    id: path.basename(e),
                    title: getProperty(str, 'title'),
                    tag: getProperty(str, 'tag'),
                    key: getProperty(str, 'key'),
                    description: getProperty(str, 'description'),
                    deprecated: getProperty(str, 'deprecated'),
                }
            })

        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(capabilitys));
    } catch (error) {
        res.statusCode = 500;
        res.end();
    }
}

function getDirectories(source: string): string[] {
    return fs.readdirSync(source, { withFileTypes: true })
        .filter(dirent => dirent.isDirectory())
        .map(dirent => path.join(source, dirent.name));
}

/** 获取属性 */
function getProperty(str: string, key: string): string | null {
    const match = str.match(new RegExp(`@${key}\\s+(.*?)\\s`, "s"));
    return match ? match[1] : null;
}